<?php

class Autorize extends Controller {

    function Autorize() {
        parent::Controller();
        $this->load->helper('form');
        $this->load->library('session');
        $this->load->model('Auth');
        $ckeck = $this->Auth->login($this->session->userdata('login'));
        if ($this->session->userdata('hash') != '' && $ckeck->Hash == $this->session->userdata('hash'))
            return;
        if ($this->uri->segment(2) === 'login')
            return;
        redirect('autorize/login');
    }

    function login() {


        if (!is_file($this->config->item('sgconf_xml'))) {

            $this->load->view('errors/header', $data);
            $this->load->view('errors/kk', $data);
            $this->load->view('errors/footer', $data);
        } else {

            if (preg_match("#[a-zA-Z0-9_\-.]+#Uis", $_POST['password']) && preg_match("#[a-zA-Z0-9_\-.]+#Uis", $_POST['login']))
                $cmd = shell_exec($this->config->item('sgconf_xml') . " -s " . $this->config->item('stg_host') . " -p " . $this->config->item('stg_port') . " -a " . $_POST['login'] . " -w " . $_POST['password'] . " -r '<GetServerInfo/>'");

            if (preg_match("#<ServerInfo>(.*)</ServerInfo>#Uis", $cmd, $info)) {

                $md5 = md5(rand(1, 999999));

                $this->db->query('delete from Auth where User = "' . $_POST['login'] . '"');
                $this->db->query('insert into Auth (User,Hash) values("' . $_POST['login'] . '","' . $md5 . '") ');

                $session_data = array('login' => $_POST['login'], 'info' => $info[0], 'hash' => $md5);
                $this->session->set_userdata($session_data);
                redirect('');
            } else {

                $data['error'] = $cmd;
            }

            $this->load->view('login', $data);
        }
    }

    function logoff() {
        $this->session->sess_destroy();
        redirect('autorize/login');
    }

}

?>
